package controllers

import (

	"fmt"
	"github.com/astaxie/beego"
	"time"
	"git.oschina.net/fanbuchi/timemaker/models"
	"encoding/json"
)

//message for someone & shomewhere & sometime
type MsgController struct {
	beego.Controller
}

const (
	msgStatus_ok = iota
	msgStatus_prePublic
	msgStatus_publiced
	msgStatus_invalid
	msgStatus_deleted
	msgStatus_protected
)

// @Author killerzhangsan
// @Title msg api check
// @Description app msg api check
// @Param   client_id     header    string  true        "The client_id"
// @Success 200 ok
// @router / [get]
func (this *MsgController) Get() {
	objectStatus := models.ObjectStatus{Status: models.Ok, Desc: "msg api ok"}
	this.Data[dataformat] = objectStatus
	this.ServeJson()
}

// @Author killerzhangsan
// @Title publicMsg
// @Description public a message
// @Param   client_id     header    string  true        "The client_id"
// @Param   basic        header  string  true        "basic token"
// @Param    msg          body    string  true        "The msg "
// @Success 200 ok
// @router /publicMsg [post]
func (this *MsgController) PublicMsg() {
	var objectStatus interface{}

	//"0= WGS84 1 Google Maps 地图模式 2百度地图坐标 3= QQ腾讯地图坐标 / 高德地图坐标 / 阿里云地图坐标 4= MapBar图吧地图坐标"
	clientdetails,err:=models.Token(this.Ctx.Input.Header("basic"))
	if err != nil {
		status := models.ObjectStatus{Status: models.ParamError, Desc: err.Error()}
		this.Data[dataformat] = status
		this.ServeJson()
		this.StopRun()
	}
	var msg models.Msg
	json.Unmarshal(this.Ctx.Input.RequestBody,&msg)
	msg.UserId=clientdetails.UserId
	msg.MapType=2
	err = models.CreateMsg(&msg)

	if err != nil {
		objectStatus = models.ObjectStatus{Status: models.ParamError, Desc:err.Error()}
	} else {
		objectStatus = msg
	}
	this.Data[dataformat] = objectStatus
	this.ServeJson()
}

// @Author killerzhangsan
// @Title delMsg
// @Description delete a message
// @Param   client_id     header    string  true        "The client_id"
// @Param   basic        header  string  true        "basic token"
// @Param    msg_id    query    string  true        "The msg_id for key"
// @Success 200 ok
// @router /delMsg [put]
func (this *MsgController) DelMsg() {
	clientdetails,err:=models.Token(this.Ctx.Input.Header("basic"))
	if err != nil {
		status := models.ObjectStatus{Status: models.ParamError, Desc: err.Error()}
		this.Data[dataformat] = status
		this.ServeJson()
		this.StopRun()
	}

	msg_Id := this.GetString("msg_id")
	msg:=models.Msg{MsgId:msg_Id,
					Status:msgStatus_deleted,
					UserId:clientdetails.UserId,
					}
	_, err = models.UpdateStatus(&msg)
	var objectStatus models.ObjectStatus
	if err != nil {
		objectStatus = models.ObjectStatus{Status: models.BusinessError, Desc: err.Error()}
	} else {
		objectStatus = models.ObjectStatus{Status: models.Ok, Desc: "msg del success"}
	}
	this.Data[dataformat] = objectStatus
	this.ServeJson()
}

// @Author killerzhangsan
// @Title protectedMsg
// @Description protected a message
// @Param   client_id     header    string  true        "The client_id"
// @Param   basic        header  string  true        "basic token"
// @Param    msg_id    query    string  true        "The msg_id for key"
// @Success 200 ok
// @router /protectedMsg [put]
func (this *MsgController) ProtectedMsg() {
	msg_Id := this.GetString("msg_id")

	clientdetails,err:=models.Token(this.Ctx.Input.Header("basic"))
	if err != nil {
		status := models.ObjectStatus{Status: models.ParamError, Desc: err.Error()}
		this.Data[dataformat] = status
		this.ServeJson()
		this.StopRun()
	}
	msg:=models.Msg{MsgId:msg_Id,
		Status:msgStatus_protected,
		UserId:clientdetails.UserId,
	}
	_, err = models.UpdateStatus(&msg)
	var objectStatus models.ObjectStatus
	if err != nil {
		objectStatus = models.ObjectStatus{Status: models.BusinessError, Desc: err.Error()}
	} else {
		objectStatus = models.ObjectStatus{Status: models.Ok, Desc: "msg protected success"}
	}
	this.Data[dataformat] = objectStatus
	this.ServeJson()
}

// @Author killerzhangsan
// @Title editMsg
// @Description edit a message
// @Param   client_id     header    string  true        "The client_id"
// @Param   basic        header  string  true        "basic token"
// @Param    msg_id    query    string  true        "The msg_id for key"
// @Param    content    body    string  true        "The content for edit"
// @Success 200 ok
// @router /editMsg [post]
func (this *MsgController) EditMsg() {
	clientdetails,err:=models.Token(this.Ctx.Input.Header("basic"))
	if err != nil {
		status := models.ObjectStatus{Status: models.ParamError, Desc: err.Error()}
		this.Data[dataformat] = status
		this.ServeJson()
		this.StopRun()
	}

	msg_Id := this.GetString("msg_id")
	content := string(this.Ctx.Input.RequestBody)
	msg:=models.Msg{MsgId:msg_Id,
		UserId:clientdetails.UserId,
		Content:content,
	}
	_, err = models.UpdateContent(&msg)
	var objectStatus models.ObjectStatus
	if err != nil {
		objectStatus = models.ObjectStatus{Status: models.BusinessError, Desc: err.Error()}
	} else {
		objectStatus = models.ObjectStatus{Status: models.Ok, Desc: "msg edit success"}
	}
	this.Data[dataformat] = objectStatus
	this.ServeJson()
}

// @Author killerzhangsan
// @Title getMsgById
// @Description get a message
// @Param   client_id     header    string  true        "The client_id"
// @Param   basic        header  string  true        "basic token"
// @Param    msg_id    query    string  true        "The msg_id for key"
// @Success 200 ok
// @router /getMsgById [get]
func (this *MsgController) GetMsgById() {
	msg_Id := this.GetString("msg_id")
	msg, err := models.GetMsgById(msg_Id)

	if err != nil {
		objectStatus := models.ObjectStatus{Status: models.BusinessError, Desc: err.Error()}
		this.Data[dataformat] = objectStatus
	} else {
		this.Data[dataformat] = msg
	}
	this.ServeJson()
}

// @Author killerzhangsan
// @Title getMsgsByPage
// @Description get a message list
// @Param   client_id     header    string  true        "The client_id"
// @Param   basic        header  string  true        "basic token"
// @Param    page    query    uint  true        "The page for key"
// @Param    page_size    query    uint  true        "The page_size for key"
// @Success 200 ok
// @router /getMsgsByPage [get]
func (this *MsgController) GetMsgsByPage() {
	var data interface{}
	var page models.Pages
	this.ParseForm(&page)
	 msgs,err:=models.GetMsgListByNear(page)
	if err!=nil {
		data=err.Error()
	}else{
		data=msgs
	}
	this.Data[dataformat] = data
	this.ServeJson()
}

func (this *MsgController) GetMsgsLast() {

	msg := models.Msg{MsgId: "日志",
		Title:       "日志",
		Content:     "这是一个用来处理日志的库，它的设计思路来自于 database/sql，目前支持的引擎有 file、console、net、smtp，可以通过如下方式进行安装：",
		PushTimes:   time.Now().Unix(),
		CreateTimes: time.Now().Unix(),
		Target:      "15108280907",
		Channel:     "sms",
		Status:      1,
	}

	msg2 := models.Msg{MsgId: "类型 [n]T 是一个有 n 个类型为 T 的值的数组。",
		Title:       "var a [10]int",
		Content:     "数组的长度是其类型的一部分，因此数组不能改变大小。 这看起来是一个制约，但是请不要担心； Go 提供了更加便利的方式来使用数组。",
		PushTimes:   time.Now().Unix(),
		CreateTimes: time.Now().Unix(),
		Target:      "15108280907",
		Channel:     "sms",
		Status:      1,
	}

	var msgs [2]models.Msg
	msgs[0] = msg
	msgs[1] = msg2
	this.Data[dataformat] = msgs
	this.ServeJson()
}

func (this *MsgController) GetMsgsByTag() {

	msg := models.Msg{MsgId: "slice1",
		Title:       "slice1",
		Content:     "一个 slice 会指向一个序列的值，并且包含了长度信息。",
		PushTimes:   time.Now().Unix(),
		CreateTimes: time.Now().Unix(),
		Target:      "15108280907",
		Channel:     "sms",
		Status:      1,
	}

	msg2 := models.Msg{MsgId: "slice2",
		Title:       "slice2",
		Content:     "一个 slice 会指向一个序列的值，并且包含了长度信息。",
		PushTimes:   time.Now().Unix(),
		CreateTimes: time.Now().Unix(),
		Target:      "15108280907",
		Channel:     "sms",
		Status:      1,
	}

	//var msgs = [2]Msg{msg,msg2}

	slice := []models.Msg{msg, msg2}
	sliceinit := make([]models.Msg, 3)

	var z []int
	fmt.Println(z, len(z), cap(z))

	fmt.Printf("%s len=%d cap=%d %v\n", "sliceinit ", len(sliceinit), cap(sliceinit), sliceinit)

	this.Data[dataformat] = slice[1:len(slice)]

	this.Data[dataformat] = sliceinit[0:len(sliceinit)]

	this.ServeJson()
}

func (this *MsgController) Prepare() {
	token := this.GetString("token")
	if token != "" {
		this.Data[dataformat] = "token=" + token
		this.ServeJson()
		this.StopRun()
	}

}

func (this *MsgController) Finish() {

}
